package main

import (
	"common"
	"common/log"
	"common/process"
	"errors"
	"euplink"
	"fmt"
	"github.com/spf13/cobra"
	"strconv"
)

var uploadCmd = &cobra.Command{
	Use:   "upload",
	Short: "上传",
	Long:  "euplink upload (local_src) (remote_dsc) (inline)",
	RunE:  cmdUpload,
}

func cmdUpload(cmd *cobra.Command, args []string) error {
	ctx, _ := process.Ctx(cmd)
	if len(args) < 2 {
		return errors.New("参数错误")
	}
	var inline = false
	if len(args) == 3 {
		inlineParam, err := strconv.Atoi(args[2])
		if err == nil {
			inline = inlineParam == 1
		}
	}

	zapLog := log.NewZapLog(&runConfig.Log)
	prj, err := euplink.NewProject(ctx, runConfig.Project, zapLog)
	if err != nil {
		return fmt.Errorf("project init err: %s", err)
	}
	prj.StartUpdateNodeServer(ctx)
	fp, size, err := common.OpenFile(args[0])
	if err != nil {
		return fmt.Errorf("open file:%s error: %s", args[0], err)
	}
	return prj.UploadObject(ctx, runConfig.Project.DefaultBucket, args[1], fp, inline, size, nil)
}
